package com.ruoyi.basedata.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.basedata.domain.*;
import com.ruoyi.basedata.domain.vo.EnergyExcelVo;
import com.ruoyi.basedata.mapper.*;
import com.ruoyi.basedata.service.IMeterSheetsService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.poi.bean.CommonColumn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.basedata.service.IElectricityAreaReportService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import javax.servlet.http.HttpServletResponse;

/**
 * 区域能耗报
Service业务层处理
 *
 * @author gdqt
 * @date 2025-03-10
 */
@Service
public class ElectricityAreaReportServiceImpl extends ServiceImpl<ElectricityAreaReportMapper, ElectricityAreaReport> implements IElectricityAreaReportService
{
    @Autowired
    private ElectricityAreaReportMapper electricityAreaReportMapper;

    @Autowired
    private IMeterSheetsService meterSheetsService;

    @Autowired
    private ElectricityTerminalsXbMapper electricityTerminalsXbMapper;

    @Autowired
    private TerminalsXbMapper terminalsXbMapper;

    @Autowired
    private ElectricityAreaLineMapper electricityAreaLineMapper;

    @Autowired
    private MeterSheetsMapper meterSheetsMapper;

    @Autowired
    private UsersXbMapper usersXbMapper;
    /**
     * 查询区域能耗报

     *
     * @param id 区域能耗报
主键
     * @return 区域能耗报

     */
    @Override
    public ElectricityAreaReport selectElectricityAreaReportById(Long id)
    {

        return electricityAreaReportMapper.selectById(id);
    }

    /**
     * 查询区域能耗报
列表
     *
     * @param electricityAreaReport 区域能耗报

     * @return 区域能耗报

     */
    @Override
    public List<ElectricityAreaReport> selectElectricityAreaReportList(ElectricityAreaReport electricityAreaReport)
    {
        LambdaQueryWrapper<ElectricityAreaReport> queryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(electricityAreaReport.getTenantId())){
            queryWrapper.eq(ElectricityAreaReport::getTenantId,electricityAreaReport.getTenantId());
        }
        if(electricityAreaReport.getAreaId() != null){
            queryWrapper.eq(ElectricityAreaReport::getAreaId,electricityAreaReport.getAreaId());
        }
        if(!electricityAreaReport.getAreaIds().isEmpty()) {
            queryWrapper.in(ElectricityAreaReport::getAreaId, electricityAreaReport.getAreaIds());
        }
        if(!StringUtils.isEmpty(electricityAreaReport.getEnergyUseClassification())){
            queryWrapper.eq(ElectricityAreaReport::getEnergyUseClassification,electricityAreaReport.getEnergyUseClassification());
        }
        if(!StringUtils.isEmpty(electricityAreaReport.getEnergyUseItem())){
            queryWrapper.eq(ElectricityAreaReport::getEnergyUseItem,electricityAreaReport.getEnergyUseItem());
        }

        if(!StringUtils.isEmpty(electricityAreaReport.getFrozenType())){
            queryWrapper.eq(ElectricityAreaReport::getFrozenType,electricityAreaReport.getFrozenType());
        }
        if(!StringUtils.isEmpty(electricityAreaReport.getFreezeTime())){
            queryWrapper.eq(ElectricityAreaReport::getFreezeTime,electricityAreaReport.getFreezeTime());
        }
        if(!StringUtils.isEmpty(electricityAreaReport.getFreezeTime())&&!StringUtils.isEmpty(electricityAreaReport.getEnergyUseItem())){
            queryWrapper.orderByDesc(ElectricityAreaReport::getCumulativeFlow);
        }else {
            queryWrapper.orderByDesc(ElectricityAreaReport::getCumulativeFlow);
        }


        return electricityAreaReportMapper.selectList(queryWrapper);
    }

    /**
     * 新增区域能耗报

     *
     * @param electricityAreaReport 区域能耗报

     * @return 结果
     */
    @Override
    public int insertElectricityAreaReport(ElectricityAreaReport electricityAreaReport)
    {
        return electricityAreaReportMapper.insert(electricityAreaReport);
    }

    /**
     * @ kyx 2025-03-11
     * 能耗报表 能耗分项报表
     * @param energy_use_classification 1：电，2：水
     * @param energy_use_item 0：能耗报表，1：能耗分项报表
     * @param frozen_type 日报表：day 月 ：month
     * @param freezeTime 冻结时间
     * @return
     */
    @Override
    public int insertElectricityAreaReportForAll(String energy_use_classification, String energy_use_item, String frozen_type, String freezeTime) {
        if("0".equals(energy_use_item)){
            switch (energy_use_classification){
                case "1"://电 能耗报表
                        if("day".equals(frozen_type)){//日报表
                         return    electricityAreaReportMapper.insertForElectricityByDay(freezeTime);
                        }else if("month".equals(frozen_type)){//月报表
                            return  electricityAreaReportMapper.insertForElectricityByMonth(freezeTime);
                        }
                        break;
                case "2"://水 能耗报表
                    if("day".equals(frozen_type)){//日报表
                        return  electricityAreaReportMapper.insertForWaterByDay(freezeTime);
                    }else if("month".equals(frozen_type)){//月报表
                        return  electricityAreaReportMapper.insertForWaterByMonth(freezeTime);
                    }
                    break;

            }
        }else if("1".equals(energy_use_item)){//能耗分项报表
            switch (energy_use_classification){
                case "1"://电 能耗报表
                    if("day".equals(frozen_type)){//日报表
                        return electricityAreaReportMapper.insertForElectricityByDayByItem(freezeTime);
                    }else if("month".equals(frozen_type)){//月报表
                        return electricityAreaReportMapper.insertForElectricityByMonthByItem(freezeTime);
                    }

                    break;
                case "2"://水 能耗报表
                    if("day".equals(frozen_type)){//日报表
                        return electricityAreaReportMapper.insertForWaterByDayByItem(freezeTime);
                    }else if("month".equals(frozen_type)){//月报表
                        return electricityAreaReportMapper.insertForWaterByMonthByItem(freezeTime);
                    }
                    break;

            }
        }else {
            return 0;
        }

        return 0;
    }

    /**
     * 修改区域能耗报

     *
     * @param electricityAreaReport 区域能耗报

     * @return 结果
     */
    @Override
    public int updateElectricityAreaReport(ElectricityAreaReport electricityAreaReport)
    {
        return electricityAreaReportMapper.updateById(electricityAreaReport);
    }

    /**
     * 批量删除区域能耗报

     *
     * @param ids 需要删除的区域能耗报
主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteElectricityAreaReportByIds(Long[] ids)
    {
        return electricityAreaReportMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除区域能耗报
信息
     *
     * @param id 区域能耗报
主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteElectricityAreaReportById(Long id)
    {
        return electricityAreaReportMapper.deleteById(id);
    }


    /**
     * 能耗分析
     * kyx
     * @param electricityAreaReport
     * @return
     */
    public Map<String, Object> getEnergyReportListForAnalysis(ElectricityAreaReport electricityAreaReport) {
        if(electricityAreaReport == null){
            return null;
        }
        Map<String,Object> resultMap = new HashMap<>();
        //生成列属性
        //{key: 0, label: `名称`, visible: true, width:150, prop: 'areaName', fixed: 'left'},
        List<CommonColumn> columns = new ArrayList<>();
        columns.add(CommonColumn.builder().key(0).label("名称").visible(true).width(200).prop("areaName").fixed("left").build());
        columns.add(CommonColumn.builder().key(1).label("日期").visible(true).width(120).prop("freezeTime").build());
        String frozenType = electricityAreaReport.getFrozenType();//冻结类型
        String freezeTime = electricityAreaReport.getFreezeTime();//时间
        if ("hour".equals(frozenType)) {
            freezeTime = freezeTime.substring(0,10);
            for (int i = 0; i < 24; i++) {
                columns.add(CommonColumn.builder().key(2+i).label(i<10? "0"+i : ""+i).visible(true).prop("key"+(i+1)).build());
            }
        }else if ("day".equals(frozenType)) {
            freezeTime = freezeTime.substring(0, 7);
            int days =DateUtil.getLastDayOfMonth(DateUtil.parse(freezeTime,"yyyy-MM"));
            for (int i = 1; i <= days; i++) {
                columns.add(CommonColumn.builder().key(2+i).label(i<10? "0"+i : ""+i).visible(true).prop("key"+i).build());
            }
        }else if ("month".equals(frozenType)) {
            freezeTime = freezeTime.substring(0,4);
            for (int i = 1; i <= 12; i++) {
                columns.add(CommonColumn.builder().key(2+i).label(i<10? "0"+i : ""+i).visible(true).prop("key"+i).build());
            }
        }
        columns.add(CommonColumn.builder().key(columns.size()).label("合计").visible(true).prop("sumValue").fixed("right").build());
        resultMap.put("columns",columns);
//        SysUser user = SecurityUtils.getLoginUser().getUser();
        //生成数据
        //1.查询条件
        LambdaQueryWrapper<ElectricityAreaReport> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ElectricityAreaReport::getFrozenType,frozenType);
//        if (user.getSystemFlag() != Constants.SYS_FLAG_ADMIN){
//            wrapper.eq(ElectricityAreaReport::getTenantId,user.getTenantId());
//        }
        //区域
        if(!electricityAreaReport.getAreaIds().isEmpty()) {
            wrapper.in(ElectricityAreaReport::getAreaId, electricityAreaReport.getAreaIds());
        }
        //能耗分类
        wrapper.eq(ElectricityAreaReport::getEnergyUseClassification,electricityAreaReport.getEnergyUseClassification());
        //能耗分项
        String energyUseItem = !StringUtils.isEmpty(electricityAreaReport.getEnergyUseItem()) ? electricityAreaReport.getEnergyUseItem() : "0";
        wrapper.eq(ElectricityAreaReport::getEnergyUseItem,energyUseItem);
        //时间
        if("hour".equals(frozenType)){
            wrapper.ge(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,10)+" 00:00:00");
            wrapper.le(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,10)+" 23:59:59");
        } else if ("day".equals(frozenType)) {
            String month = freezeTime.substring(0, 7);
            int days =DateUtil.getLastDayOfMonth(DateUtil.parse(month,"yyyy-MM"));
            wrapper.ge(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,7)+"-01 00:00:00");
            wrapper.le(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,7)+"-"+days+" 23:59:59");
        }else {
            wrapper.ge(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,4)+"-01-01 00:00:00");
            wrapper.le(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,4)+"-12-31 23:59:59");
        }
        List<ElectricityAreaReport> list = electricityAreaReportMapper.selectList(wrapper);
        if(!list.isEmpty()){
            //根据区域ID分组
            Map<Long,List<ElectricityAreaReport>> areaDataMap = list.stream().collect(Collectors.groupingBy(ElectricityAreaReport::getAreaId));

            LambdaQueryWrapper<MeterSheets> wrapper_sheetsList = new LambdaQueryWrapper<>();
            if(!electricityAreaReport.getAreaIds().isEmpty()) {
                wrapper_sheetsList.in(MeterSheets::getId, electricityAreaReport.getAreaIds());
            }
            List<MeterSheets> sheetsList = meterSheetsMapper.selectList(wrapper_sheetsList);
            //2.查询区域信息
            //{key: 0, label: `名称`, visible: true, width:150, prop: 'areaName', fixed: 'left'},
            //List<MeterSheets> sheetsList = meterSheetsMapper.getAreaTree(1,null,null,null,null,false);
            //List<MeterSheets> newList = recursive(sheetsList,electricityAreaReport.getAreaIds());
            resultMap.put("data",recursiveData(freezeTime,sheetsList,areaDataMap,columns));
        }
        return resultMap;
    }

    /**
    * @Description: 获取能耗报表
    * @date: 2025/3/10 16:36
    * @author: zt
    */
    //        SELECT ear.* from electricity_area_report ear where ear.area_id in (300)
    //        and ear.freeze_time>= '2025-03-07' and ear.freeze_time<= '2025-03-07'
    //        and ear.frozen_type = 'day' and ear.energy_use_classification = 2 and ear.energy_use_item = 0
    @Override
    public Map<String, Object> getEnergyReportList(ElectricityAreaReport electricityAreaReport) {
        if(electricityAreaReport == null){
            return null;
        }
        Map<String,Object> resultMap = new HashMap<>();
        //生成列属性
        //{key: 0, label: `名称`, visible: true, width:150, prop: 'areaName', fixed: 'left'},
        List<CommonColumn> columns = new ArrayList<>();
        columns.add(CommonColumn.builder().key(0).label("名称").visible(true).width(200).prop("areaName").fixed("left").build());
        columns.add(CommonColumn.builder().key(1).label("日期").visible(true).width(120).prop("freezeTime").build());
        String frozenType = electricityAreaReport.getFrozenType();//冻结类型
        String freezeTime = electricityAreaReport.getFreezeTime();//时间
        if ("hour".equals(frozenType)) {
            freezeTime = freezeTime.substring(0,10);
            for (int i = 0; i < 24; i++) {
                columns.add(CommonColumn.builder().key(2+i).label(i<10? "0"+i : ""+i).visible(true).prop("key"+(i+1)).build());
            }
        }else if ("day".equals(frozenType)) {
            freezeTime = freezeTime.substring(0, 7);
            int days =DateUtil.getLastDayOfMonth(DateUtil.parse(freezeTime,"yyyy-MM"));
            for (int i = 1; i <= days; i++) {
                columns.add(CommonColumn.builder().key(2+i).label(i<10? "0"+i : ""+i).visible(true).prop("key"+i).build());
            }
        }else if ("month".equals(frozenType)) {
            freezeTime = freezeTime.substring(0,4);
            for (int i = 1; i <= 12; i++) {
                columns.add(CommonColumn.builder().key(2+i).label(i<10? "0"+i : ""+i).visible(true).prop("key"+i).build());
            }
        }
        columns.add(CommonColumn.builder().key(columns.size()).label("合计").visible(true).prop("sumValue").fixed("right").build());
        resultMap.put("columns",columns);
//        SysUser user = SecurityUtils.getLoginUser().getUser();
        //生成数据
        //1.查询条件
        LambdaQueryWrapper<ElectricityAreaReport> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ElectricityAreaReport::getFrozenType,frozenType);
//        if (user.getSystemFlag() != Constants.SYS_FLAG_ADMIN){
//            wrapper.eq(ElectricityAreaReport::getTenantId,user.getTenantId());
//        }
        //区域
        if(!electricityAreaReport.getAreaIds().isEmpty()) {
            wrapper.in(ElectricityAreaReport::getAreaId, electricityAreaReport.getAreaIds());
        }
        //能耗分类
        wrapper.eq(ElectricityAreaReport::getEnergyUseClassification,electricityAreaReport.getEnergyUseClassification());
        //能耗分项
        String energyUseItem = !StringUtils.isEmpty(electricityAreaReport.getEnergyUseItem()) ? electricityAreaReport.getEnergyUseItem() : "0";
        wrapper.eq(ElectricityAreaReport::getEnergyUseItem,energyUseItem);
        //时间
        if("hour".equals(frozenType)){
            wrapper.ge(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,10)+" 00:00:00");
            wrapper.le(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,10)+" 23:59:59");
        } else if ("day".equals(frozenType)) {
            String month = freezeTime.substring(0, 7);
            int days =DateUtil.getLastDayOfMonth(DateUtil.parse(month,"yyyy-MM"));
//            wrapper.ge(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,7)+"-01 00:00:00");
//            wrapper.le(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,7)+"-"+days+" 23:59:59");
            wrapper.ge(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,7)+"-01");
            wrapper.le(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,7)+"-"+days);
        }else {
//            wrapper.ge(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,4)+"-01-01 00:00:00");
//            wrapper.le(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,4)+"-12-31 23:59:59");
            wrapper.ge(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,4)+"-01");
            wrapper.le(ElectricityAreaReport::getFreezeTime,freezeTime.substring(0,4)+"-12");
        }
        List<ElectricityAreaReport> list = electricityAreaReportMapper.selectList(wrapper);
        if(!list.isEmpty()){
            //根据区域ID分组
            Map<Long,List<ElectricityAreaReport>> areaDataMap = list.stream().collect(Collectors.groupingBy(ElectricityAreaReport::getAreaId));

            //2.查询区域信息
            //{key: 0, label: `名称`, visible: true, width:150, prop: 'areaName', fixed: 'left'},
            List<MeterSheets> sheetsList = meterSheetsService.getAreaTree(1,null,null,null,null,false);
            List<MeterSheets> newList = recursive(sheetsList,electricityAreaReport.getAreaIds());
            resultMap.put("data",recursiveData(freezeTime,newList,areaDataMap,columns));
        }
        return resultMap;
    }

    @Override
    public void exportElectricityAreaReportList(HttpServletResponse response, ElectricityAreaReport electricityAreaReport) {
        Map<String, Object> dataMap = getEnergyReportList(electricityAreaReport);
        List<EnergyExcelVo> dataList = new ArrayList<>();
        List<CommonColumn> colList = JSONArray.parseArray(JSON.toJSONString(dataMap.get("columns")), CommonColumn.class);
        if(dataMap.containsKey("data")){
            List<EnergyExcelVo> list = JSONArray.parseArray(JSON.toJSONString(dataMap.get("data")), EnergyExcelVo.class) ;
            dataList = recursiveExportData(list);
        }
        ExcelUtil<EnergyExcelVo> util = new ExcelUtil<>(EnergyExcelVo.class);
        util.exportExcelWithColumns(response, dataList, colList, "区域能耗报表数据");
//        util.exportExcel(response, dataList, "区域能耗报表数据");
    }

    /**
     * 能耗分析报表导出
     * @param response
     * @param electricityAreaReport
     */
    @Override
    public void exportElectricityAreaReportList2(HttpServletResponse response, ElectricityAreaReport electricityAreaReport) {
        Map<String, Object> dataMap = getEnergyReportListForAnalysis(electricityAreaReport);
        List<EnergyExcelVo> dataList = new ArrayList<>();
        List<CommonColumn> colList = JSONArray.parseArray(JSON.toJSONString(dataMap.get("columns")), CommonColumn.class);
        if(dataMap.containsKey("data")){
            List<EnergyExcelVo> list = JSONArray.parseArray(JSON.toJSONString(dataMap.get("data")), EnergyExcelVo.class) ;
            dataList = recursiveExportData(list);
        }
        ExcelUtil<EnergyExcelVo> util = new ExcelUtil<>(EnergyExcelVo.class);
        util.exportExcelWithColumns(response, dataList, colList, "能耗分析报表");
//        util.exportExcel(response, dataList, "区域能耗报表数据");
    }

    public List<EnergyExcelVo> recursiveExportData(List<EnergyExcelVo> list){
        List<EnergyExcelVo> dataList = new ArrayList<>();
        for (EnergyExcelVo excelVo : list) {
            dataList.add(excelVo);
            if(excelVo.getChildren()!=null && !excelVo.getChildren().isEmpty()){
                dataList.addAll(recursiveExportData(excelVo.getChildren()));
            }
        }
        return dataList;
    }

    //递归数据
    public List<Map<String,Object>> recursiveData(String freezeTime,List<MeterSheets> sheetsList,Map<Long,List<ElectricityAreaReport>> areaDataMap,List<CommonColumn> columns){
        List<Map<String,Object>> resList = new ArrayList<>();
        for (MeterSheets meterSheets : sheetsList) {
            Map<String,Object> map = new HashMap<>();
            Long areaId = meterSheets.getId();
            List<ElectricityAreaReport> reportList = areaDataMap.get(areaId);
            //返回日期map
            Map<String,ElectricityAreaReport> reportMap = (reportList == null || reportList.isEmpty()) ? null : reportList.stream().collect(Collectors.toMap(ElectricityAreaReport::getFreezeTime, Function.identity()));
            //列{key: 0, label: `名称`, visible: true, width:150, prop: 'areaName', fixed: 'left'}
            map.put("areaId",areaId);
            double sumValue = 0;
            for (CommonColumn vo : columns) {
                if("areaName".equals(vo.getProp())){
                    map.put(vo.getProp(),meterSheets.getSheetsName());
                }else if("freezeTime".equals(vo.getProp())){
                    map.put(vo.getProp(),freezeTime);
                }else if("sumValue".equals(vo.getProp())){
                    map.put(vo.getProp(),sumValue);
                }else {
                    //日期列字段，key1,key2...
                    String label = vo.getLabel();
                    String ftime = freezeTime + " " + label + ":00:00";
                    if(freezeTime.length() == 10){//时
                        ftime = freezeTime + " " + label + ":00:00";
                    }else {//日,月
                        ftime = freezeTime + "-" + label;
                    }
                    ElectricityAreaReport temp = reportMap == null ? null : reportMap.get(ftime);
                    if(temp == null){
                        map.put(vo.getProp(),"");
                    }else {
                        map.put(vo.getProp(),temp.getCumulativeFlow());
                        sumValue += temp.getCumulativeFlow().doubleValue();
                    }
                }
            }
            if(meterSheets.getChildren()!=null && !meterSheets.getChildren().isEmpty()){
                map.put("children",recursiveData(freezeTime,meterSheets.getChildren(),areaDataMap,columns));
            }
            resList.add(map);
        }
        return resList;
    }

    //递归-过滤选择的区域
    public List<MeterSheets> recursive(List<MeterSheets> sheetsList,List<Long> areaIds){
        Iterator<MeterSheets> iterator = sheetsList.iterator();
        while (iterator.hasNext()) {
            MeterSheets sheet = iterator.next();
            Long areaId = sheet.getId();
            //包含该区域
            if(areaIds.contains(areaId)){
                sheet.setChildren(recursive(sheet.getChildren(),areaIds));
            }else {
                iterator.remove();
            }
        }
        return sheetsList;
    }


    /**
     * @Description: 能耗概况-获取磁贴中各类数据
     * @date: 2025/3/13 10:45
     * @author: zt
     */
    @Override
    public List<Object> getSummarizeList() {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        String currentMonth = DateUtil.format(new Date(), "yyyy-MM");
        int lastDay = DateUtil.getLastDayOfMonth(new Date());
        String startDay = currentMonth+"-01";
        String endDay = currentMonth+"-"+(lastDay<10?"0"+lastDay:""+lastDay);
        List<Object> resList = new ArrayList<>();
        // 供电房数量（暂时写0）-更改为客户数量
        LambdaQueryWrapper<UsersXb> wrapper = new LambdaQueryWrapper<UsersXb>();
        wrapper.eq(UsersXb::getDelFlag,0);
        if(!sysUser.getSystemFlag().equals(Constants.SYS_FLAG_ADMIN)){
            wrapper.eq(UsersXb::getTenantId,sysUser.getTenantId());
        }
        int userNum = usersXbMapper.selectList(wrapper).size();
        resList.add(userNum);
        //终端设备数（目前用水表数量+电表数量）
        //电
        List<ElectricityTerminalsXb> elecTerminalList = electricityTerminalsXbMapper.selectList(new LambdaQueryWrapper<ElectricityTerminalsXb>()
                .eq(ElectricityTerminalsXb::getTenantId,sysUser.getTenantId()).eq(ElectricityTerminalsXb::getDelFlag,0).eq(ElectricityTerminalsXb::getTerminalMark,1));
        //水
        List<TerminalsXb> terminalList = terminalsXbMapper.selectList(new LambdaQueryWrapper<TerminalsXb>()
                .eq(TerminalsXb::getTenantId,sysUser.getTenantId()).eq(TerminalsXb::getDelFlag,0).eq(TerminalsXb::getTerminalMark,1));
        resList.add(elecTerminalList.size()+terminalList.size());

        // 小区数量（统计区域长度为6的，例如：091001）、
        int count = electricityAreaReportMapper.countSheetsWithUserId(sysUser.getUserId());
        resList.add(count);
        // 总能耗量、
        List<MeterSheets> sheetsList = meterSheetsService.getAreaTree(1,null,null,null,null,false);

//        List<String> lv1SheetsCode = sheetsList.stream().map(MeterSheets::getSheetsCode).collect(Collectors.toList());

//        List<Long> areaIds = sheetsList.stream().map(MeterSheets::getId).collect(Collectors.toList());
        //所有节点areaId
//        List<Long> areaIds = recursiveAreaIds(sheetsList);
        //最下级
        List<MeterSheets> lastList = recursiveLast(sheetsList);
        List<Long> areaIds = lastList.stream().map(MeterSheets::getId).collect(Collectors.toList());
        List<ElectricityAreaReport> reportList = electricityAreaReportMapper.selectList(new LambdaQueryWrapper<ElectricityAreaReport>()
                .in(ElectricityAreaReport::getAreaId,areaIds)
                .eq(ElectricityAreaReport::getFrozenType,"day")
                .eq(ElectricityAreaReport::getEnergyUseItem,0)
                .eq(ElectricityAreaReport::getEnergyUseClassification,1)
                .ge(ElectricityAreaReport::getFreezeTime,startDay)
                .le(ElectricityAreaReport::getFreezeTime,endDay));
        double reportValue = reportList.stream().mapToDouble(item -> item.getCumulativeFlow() != null ? item.getCumulativeFlow().doubleValue() : 0L).sum();
        BigDecimal bd = new BigDecimal(reportValue);
        double newReportValue = bd.setScale(2, RoundingMode.HALF_UP).doubleValue();
        resList.add(newReportValue);
        // 总线损、
        List<ElectricityAreaLine> lineLossList = electricityAreaLineMapper.selectList(new LambdaQueryWrapper<ElectricityAreaLine>()
                .in(ElectricityAreaLine::getAreaId,areaIds)
                .eq(ElectricityAreaLine::getFrozenType,"day")
                .eq(ElectricityAreaLine::getEnergyUseClassification,1)
                .ge(ElectricityAreaLine::getFreezeTime,startDay)
                .le(ElectricityAreaLine::getFreezeTime,endDay));
        double lineLossValue = lineLossList.stream().mapToDouble(item -> item.getLineLoss() != null ? item.getLineLoss().doubleValue() : 0L).sum();
        BigDecimal bd2 = new BigDecimal(lineLossValue);
        double lineLossValue2 = bd2.setScale(2, RoundingMode.HALF_UP).doubleValue();
        resList.add(lineLossValue2);
        return resList;
    }

    //递归区域ID
    public List<Long> recursiveAreaIds(List<MeterSheets> sheetsList){
        List<Long> areaIds = new ArrayList<>();
        if(!sheetsList.isEmpty()){
            for(MeterSheets sheet : sheetsList){
                areaIds.add(sheet.getId());
                if(sheet.getChildren()!=null && !sheet.getChildren().isEmpty()){
                    areaIds.addAll(recursiveAreaIds(sheet.getChildren()));
                }
            }
        }
        return areaIds;
    }

    /**
     * @Description: 能耗概况-当月园区线损情况
     * @date: 2025/3/13 15:33
     * @author: zt
     */
    @Override
    public Map<String, Object> getLineLossMonthList() {
        Map<String,Object> resMap = new HashMap<>();
        List<String> dayMonthList = new ArrayList<>();
        List<Double> inDataList = new ArrayList<>();
        List<Double> outDataList = new ArrayList<>();
        List<Double> lineLossRateList = new ArrayList<>();
        String currentMonth = DateUtil.format(new Date(), "yyyy-MM");
        int lastDay = DateUtil.getLastDayOfMonth(new Date());
        String startDay = currentMonth+"-01";
        String endDay = currentMonth+"-"+(lastDay<10?"0"+lastDay:""+lastDay);
//        当月、该用户匹配区域下的最高级区域线损情况：
//        数据类型为日（day）,总进用能、下级出用能、线损率，前两个用重叠柱状图显示，线损率用曲线显示，若是最高级区域有多个，需要将总进用能相加、下级出用能相加、线损率相加求平均值；
        List<MeterSheets> sheetsList = meterSheetsService.getAreaTree(1,null,null,null,null,false);
        //顶级区域ID
//        List<Long> areaIds = sheetsList.stream().map(MeterSheets::getId).collect(Collectors.toList());
        //最下级
        List<MeterSheets> lastList = recursiveLast(sheetsList);
        List<Long> areaIds = lastList.stream().map(MeterSheets::getId).collect(Collectors.toList());
        List<ElectricityAreaLine> lineLossList = electricityAreaLineMapper.selectList(new LambdaQueryWrapper<ElectricityAreaLine>()
                .in(ElectricityAreaLine::getAreaId,areaIds)
                .eq(ElectricityAreaLine::getFrozenType,"day")
                .eq(ElectricityAreaLine::getEnergyUseClassification,1)
                .ge(ElectricityAreaLine::getFreezeTime,startDay)
                .le(ElectricityAreaLine::getFreezeTime,endDay));
        //根据冻结日期分组
        Map<String,List<ElectricityAreaLine>> timeMap = lineLossList.stream().collect(Collectors.groupingBy(ElectricityAreaLine::getFreezeTime));
        //计算日
        for (int i = 1; i <= lastDay; i++) {
            //日期
            String tempDay = currentMonth + "-" + (i<10?"0"+i:""+i);
            dayMonthList.add(tempDay);
            //该日有数据
            double inValue = 0;
            double outValue = 0;
            double lineLossRateValue = 0;
            if(timeMap.containsKey(tempDay)){
                inValue = timeMap.get(tempDay).stream().mapToDouble(item -> item.getEnterPower() != null ? item.getEnterPower().doubleValue() : 0L).sum();
                outValue = timeMap.get(tempDay).stream().mapToDouble(item -> item.getOutputPower() != null ? item.getOutputPower().doubleValue() : 0L).sum();
                lineLossRateValue = timeMap.get(tempDay).stream().mapToDouble(item -> item.getLineLossRate() != null ? item.getLineLossRate().doubleValue() : 0L).sum();
            }
            //总进用能
            inDataList.add(inValue);
            //下级出用能
            outDataList.add(outValue);
            //线损率
            lineLossRateList.add(lineLossRateValue);
        }
        resMap.put("dayMonthList",dayMonthList);
        resMap.put("inDataList",inDataList);
        resMap.put("outDataList",outDataList);
        resMap.put("lineLossRateList",lineLossRateList);
        return resMap;
    }

    /**
     * @Description: 能耗概况-当日园区总负荷
     * @date: 2025/3/13 15:33
     * @author: zt
     */
    @Override
    public Map<String, Object> getEnergyDayList() {
        //展示昨天、该用户匹配区域下的最低级区域能耗情况（如何sql查出匹配下最低级的区域）：
        //数据类型为时（hour）,当日最高、最低与昨日最高最低需要前端或者后端计算，若是最低级区域有多个，需要将用能相加；
        Map<String,Object> resMap = new HashMap<>();
        List<String> dayMonthList = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            String temoHour = (i<10?"0"+i:""+i)+":00";
            dayMonthList.add(temoHour);
        }
        String todayDate = DateUtil.format(new Date(), "yyyy-MM-dd");
        String yesterDayDate = DateUtil.format(DateUtil.yesterday().toJdkDate(), "yyyy-MM-dd");
        List<MeterSheets> sheetsList = meterSheetsService.getAreaTree(1,null,null,null,null,false);
        //最下级
        List<MeterSheets> lastList = recursiveLast(sheetsList);
        List<Long> areaIds = lastList.stream().map(MeterSheets::getId).collect(Collectors.toList());
        Map<String,Object> yesterDayMap = getLastAreaReport(areaIds,yesterDayDate);
        Map<String,Object> todayMap = getLastAreaReport(areaIds,todayDate);
        resMap.put("dayMonthList",dayMonthList);
        resMap.put("yesterDayMap",yesterDayMap);
        resMap.put("todayMap",todayMap);
        return resMap;
    }


    /**
    * @Description: type:0 昨日 ；type:1 今日
    * @date: 2025/3/14 13:43
    * @author: zt
    */
    public Map<String,Object> getLastAreaReport(List<Long> areaIds,String date){
        String startDay = date+" 00:00:00";
        String endDay = date+" 23:59:59";
        List<Double> hourDataList = new ArrayList<>();
        List<ElectricityAreaReport> reportList = electricityAreaReportMapper.selectList(new LambdaQueryWrapper<ElectricityAreaReport>()
                .in(ElectricityAreaReport::getAreaId,areaIds)
                .eq(ElectricityAreaReport::getFrozenType,"hour")
                .eq(ElectricityAreaReport::getEnergyUseClassification,1)
                .ge(ElectricityAreaReport::getFreezeTime,startDay)
                .le(ElectricityAreaReport::getFreezeTime,endDay));
        //根据冻结日期分组
        Map<String,List<ElectricityAreaReport>> timeMap = reportList.stream().collect(Collectors.groupingBy(ElectricityAreaReport::getFreezeTime));

        double maxValue = 0;
        String maxHour = "";
        double minValue = 0;
        String minHour = "";
        //计算时
        for (int i = 0; i < 24; i++) {
            //日期
            String datetime = date + " " + (i<10?"0"+i:""+i) + ":00:00";
            String tempHour = (i<10?"0"+i:""+i)+":00";
            //该日有数据
            double value = 0;
            if(timeMap.containsKey(datetime)){
                value = timeMap.get(datetime).stream().mapToDouble(item -> item.getCumulativeFlow() != null ? item.getCumulativeFlow().doubleValue() : 0L).sum();
            }
            hourDataList.add(value);
            if(maxValue<=value){
                maxValue = value;
                maxHour = tempHour;
            }
            if(minValue>=value){
                minValue = value;
                minHour = tempHour;
            }
        }
        Map<String,Object> resMap = new HashMap<>();
        resMap.put("hourDataList",hourDataList);
        resMap.put("maxValue",maxValue);
        resMap.put("maxHour",maxHour);
        resMap.put("minValue",minValue);
        resMap.put("minHour",minHour);
        return resMap;
    }

    /**
    * @Description: 返回最下级区域
    * @date: 2025/3/14 13:23
    * @author: zt
    */
    public List<MeterSheets> recursiveLast(List<MeterSheets> sheetsList){
        List<MeterSheets> lastList = new ArrayList<>();
        for (MeterSheets sheet : sheetsList) {
            if (sheet.getChildren() != null && !sheet.getChildren().isEmpty()) {
                lastList.addAll(recursiveLast(sheet.getChildren()));
            } else {
                lastList.add(sheet);
            }
        }
        return lastList;
    }
}
